<template>
  <div class="page-container">
    <!--工具栏-->
    <div class="toolbar" style="padding-left:15px;">
      <el-form :inline="true" :model="filters" :size="size" ref="filters">
        <el-row class="search-input">
          <el-form-item prop="logisticsCompanyNo" label="物流公司编号：">
            <el-input v-model="filters.logisticsCompanyNo" placeholder="物流公司编号"></el-input>
          </el-form-item>
          <el-form-item prop="logisticsCompanyName" label="物流公司名称：">
            <el-input v-model="filters.logisticsCompanyName" placeholder="物流公司名称"></el-input>
          </el-form-item>
        </el-row>
        <el-row class="search-button button20">
          <el-form-item>
            <kt-button
              icon="fa fa-search"
              :label="$t('action.search')"
              type="primary"
              @click="findPage(null)"
            />
          </el-form-item>
          <el-form-item>
            <kt-button
              icon="fa fa-plus"
              :label="$t('action.add')"
              type="primary"
              @click="handleAdd"
            />
          </el-form-item>
          <el-form-item>
            <kt-button
              icon="fa fa-refresh"
              :label="$t('action.reset')"
              type="primary"
              @click="resetForm('filters')"
            />
          </el-form-item>
        </el-row>
      </el-form>
    </div>
    <el-row class="t_r button20">
      <el-button-group>
        <el-tooltip content="刷新" placement="top">
          <el-button icon="fa fa-refresh" @click="findPage(null)"></el-button>
        </el-tooltip>
        <el-tooltip content="列显示" placement="top">
          <el-button icon="fa fa-filter" @click="displayFilterColumnsDialog"></el-button>
        </el-tooltip>
        <el-tooltip content="导出" placement="top">
          <el-button icon="fa fa-file-excel-o" @click="downloadExcel"></el-button>
        </el-tooltip>
      </el-button-group>
    </el-row>
    <div class="toolbar" style="float:right;padding-right:15px;">
      <!--表格显示列界面-->
      <table-column-filter-dialog
        ref="tableColumnFilterDialog"
        :columns="columns"
        @handleFilterColumns="handleFilterColumns"
      ></table-column-filter-dialog>
    </div>
    <!--表格内容栏-->
    <!--表格内容栏-->
    <cy-table
      :height="350"
      :highlightCurrentRow="true"
      :content="pageResult"
      :totalSize="totalSize"
      :columns="filterColumns"
      :showBatchDelete="true"
      @selectionChange="selectionChange"
      @findPage="findPage"
      @handleEdit="handleEdit"
      :btnList="btnList"
      :showDeleteOperation="false"
      @handleDelete1="handleDelete1"
      @handleDelete="handleDelete"
      ref="CyTable"
    ></cy-table>
    <!--新增编辑界面-->
    <el-dialog
      :title="operation?'新增':'编辑'"
      width="45%"
      :visible.sync="editDialogVisible"
      :close-on-click-modal="false"
    >
      <el-form
        :model="dataForm"
        label-width="140px"
        :rules="dataFormRules"
        ref="dataForm"
        :size="size"
      >
        <div style="text-align:center" class="pt20">
          <el-radio-group v-model="dataForm.source" @change="changeSource">
            <el-radio :label="1">系统配送商</el-radio>
            <el-radio :label="2">自定义配送商</el-radio>
          </el-radio-group>
        </div>
        <el-row class="searchDialog-input">
          <el-form-item label="id：" prop="id" v-if="false">
            <el-input
              v-model="dataForm.id"
              :disabled="true"
              auto-complete="off"
              placeholder="请输入ID"
            ></el-input>
          </el-form-item>
          <el-form-item label="物流公司名称：" prop="logisticsCompanyName" v-if="deliveryCompanyNameShow">
            <el-input
              v-model="dataForm.logisticsCompanyName"
              auto-complete="off"
              placeholder="请输入物流公司名称"
            ></el-input>
          </el-form-item>
          <el-form-item label="物流公司名称：" prop="logisticsCompanyName" v-if="deliverySelectCompanyNameShow">
            <el-select
              v-model="dataForm.logisticsCompanyName"
              placeholder="请选择"
              style="width: 100%"
              value-key="flagID"
              @change="changeLogisticsCompanyName"
            >
              <el-option
                v-for="item in logisticsCompanyNameOptions"
                :key="item.flagID"
                :label="item.deliveryCompanyName"
                :value="item"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="物流公司编号：" prop="logisticsCompanyNo">
            <el-input
              v-model="dataForm.logisticsCompanyNo"
              auto-complete="off"
              :disabled="logisticsCompanyNoDisabled"
              placeholder="请输入物流公司编号"
            ></el-input>
          </el-form-item>
          <el-form-item label="联系电话：" prop="telephone">
            <el-input v-model="dataForm.telephone" auto-complete="off" placeholder="请输入联系电话"></el-input>
          </el-form-item>
          <el-form-item label="状态：" prop="status">
            <el-radio-group v-model="dataForm.status">
              <el-radio :label="1">启用</el-radio>
              <el-radio :label="2">停用</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="配送公司Logo：" prop="logisticsCompanyLogo" v-if="showLogo">
            <el-upload
              class="upload-demo"
              :action="imgUpload"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              :on-exceed="handleExceed"
              :before-upload="beforeArticleUpload"
              :on-success="handleArticleSuccess"
              :file-list="fileList"
              list-type="picture-card"
              :limit="imageSizeLimit"
              :accept="imageAccept"
            >
              <i class="el-icon-plus"></i>
            </el-upload>
          </el-form-item>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer" style="text-align:center">
        <el-button :size="size" @click.native="editDialogVisible = false">{{$t('action.cancel')}}</el-button>
        <el-button
          :size="size"
          type="primary"
          @click.native="submitForm"
          :loading="editLoading"
        >{{$t('action.submit')}}</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
//import CyTable from "@/views/Core/CyTable";
import KtButton from "@/views/Core/KtButton";
import { format } from "@/utils/datetime";
import TableColumnFilterDialog from "@/views/Core/TableColumnFilterDialog";
import CyTable from "@/views/Core/ProductTable";
import { exportExcel } from "@/utils/excel";

export default {
  components: {
    CyTable,
    KtButton,
    TableColumnFilterDialog
  },
  data() {
    return {
      showLogo: true,
      imageSizeLimit: 1, //图片上传个数控制
      imageAccept: ".jpg,.jpeg,.png,.JPG,.JPEG", //图片上传格式
      fileList: [],
      imgUpload: this.utils.getUpLoadHost1(),
      paramDelete: {},
      logisticsCompanyNoDisabled: false,
      btnList: [
        {
          customLabel: "删除",
          isShowMethod: 2,
          method: "handleDelete1"
        }
      ],
      logisticsCompanyNameOptions: [],
      size: "small",
      filters: {
        logisticsCompanyNo: "",
        logisticsCompanyName: ""
      },
      columns: [
        { prop: "logisticsCompanyName", label: "物流公司名称", minWidth: 50 },
        { prop: "logisticsCompanyNo", label: "物流公司编号", minWidth: 120 },
        { prop: "telephone", label: "联系电话", minWidth: 120 },
        {
          prop: "status",
          label: "状态",
          minWidth: 120,
          formatter: this.showOrderStatus
        },
        {
          prop: "source",
          label: "配送商来源",
          minWidth: 120,
          formatter: this.showOrdersource
        }
      ],
      filterColumns: [],
      pageRequest: { pageNum: 1, pageSize: 10 },
      pageResult: [],
      totalSize: 0,
      operation: false, // true:新增, false:编辑
      editDialogVisible: false, // 新增编辑界面是否显示
      editDialogVisibleMatching: false,
      editLoading: false,
      deliveryCompanyNameShow: true,
      deliverySelectCompanyNameShow: false,
      dataFormRules: {
        logisticsCompanyName: [
          { required: true, message: "请输入物流公司名称", trigger: "change" }
        ],
        logisticsCompanyNo: [
          { required: true, message: "请输入物流公司编号", trigger: "blur" }
        ]
        // logisticsCompanyLogo:[{ required: true, message: "请上传Logo", trigger: "blur" }],
      },
      // 新增编辑界面数据
      dataForm: {
        status: 1,
        logisticsCompanyName: "",
        logisticsCompanyNo: "",
        telephone: "",
        source: 2,
        logisticsCompanyLogo: ""
      },
      checked: []
    };
  },
  methods: {
    //系统快递公司初始化
    queryExpressMapConfig() {
      let this_ = this;
      this.utils.request.queryExpressMapConfig({}, function(data) {
        if (data.data != null) {
          this_.logisticsCompanyNameOptions = data.data;
        }
      });
    },
    //图片移除
    handleRemove(file, fileList) {
      if (fileList && fileList.length == 0) {
        this.dataForm.logisticsCompanyLogo = "";
      }
    },
    //上传图片成功
    handleArticleSuccess: function(res, file) {
      if (res && res.code == "0000" && res.data && res.data.imgUrl) {
        this.dataForm.logisticsCompanyLogo = res.data.imgUrl;
        this.fileList.push(res.data.imgUrl);
      }
      this.$message({
        message: "上传成功!",
        type: "success"
      });
    },
    //上传图片校验
    beforeArticleUpload(file) {
      var size = 2,
        this_ = this;
      const isLt2M = file.size / 1024 / 1024 < size;
      if (!isLt2M) {
        this_.$message.error("上传图片大小不能超过" + size + " MB!");
      }
      //jpg,jpeg,png,JPG,JPEG
      const isJPG =
        file.type === "image/jpeg" ||
        file.type === "image/png" ||
        file.type === "image/jpg" ||
        file.type === "image/JPG" ||
        file.type === "image/JPEG" ||
        file.type === "image/PNG";
      if (!isJPG) {
        this_.$message.error(
          "上传图片只能是jpeg、png、jpg、JPG、JPEG、PNG 格式!"
        );
      }
    },
    //上传图片校验
    beforeArticleUpload(file) {
      var size = 2,
        this_ = this;
      const isLt2M = file.size / 1024 / 1024 < size;
      if (!isLt2M) {
        this_.$message.error("上传图片大小不能超过" + size + " MB!");
      }
      //jpg,jpeg,png,JPG,JPEG
      const isJPG =
        file.type === "image/jpeg" ||
        file.type === "image/png" ||
        file.type === "image/jpg" ||
        file.type === "image/JPG" ||
        file.type === "image/JPEG" ||
        file.type === "image/PNG";
      if (!isJPG) {
        this_.$message.error(
          "上传图片只能是jpeg、png、jpg、JPG、JPEG、PNG 格式!"
        );
      }
    },
    handlePreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    handleExceed: function() {
      this.$alert("最多上传一张", "警告", {
        confirmButtonText: "确定"
      });
    },
    handlePreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    changeLogisticsCompanyName(param) {
      this.dataForm.logisticsCompanyNo = param.deliveryCompanyCode;
      this.dataForm.logisticsCompanyName = param.deliveryCompanyName;
      this.dataForm.logisticsCompanyLogo = param.deliveryCompanyLogo;
    },
    changeSource(param) {
      if (param == 1) {
        this.dataForm.status = 1;
        this.dataForm.logisticsCompanyName = "";
        this.dataForm.logisticsCompanyNo = "";
        this.dataForm.telephone = "";
        this.dataForm.source = 1;
        // this.dataForm={
        //     status: 1,
        //     logisticsCompanyName: '',
        //     logisticsCompanyNo: "",
        //     telephone: "",
        //     source: 1,
        // },

        this.deliveryCompanyNameShow = false;
        this.deliverySelectCompanyNameShow = true;
        this.logisticsCompanyNoDisabled = true;
        this.showLogo = false;
      } else {
        let this_ = this;
        this_.dataForm.status = 1;
        this_.dataForm.logisticsCompanyName = "";
        this_.dataForm.logisticsCompanyNo = "";
        this_.dataForm.telephone = "";
        this_.dataForm.source = 2;
        this_.fileList = [];
        this_.showLogo = true;
        // this.dataForm={
        //   status: 1,
        //   logisticsCompanyName: '',
        //   logisticsCompanyNo: "",
        //   telephone: "",
        //   source: 2,
        // },
        // this_.$refs['dataForm'].resetFields();
        this_.deliveryCompanyNameShow = true;
        this_.deliverySelectCompanyNameShow = false;
        this_.logisticsCompanyNoDisabled = false;
      }
    },
    handleDelete1(param) {
      let params = [];
      this.open();
      params.push(param.row);
      this.paramDelete.params = params;
    },
    open() {
      this.$confirm("确认删除选中记录吗?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          this.handleDelete(this.paramDelete);
        })
        .catch(() => {});
    },

    //状态初始化
    showOrderStatus(row, column, cellValue, index) {
      if (cellValue == "1") {
        return "启用";
      } else if (cellValue == "2") {
        return "停用";
      }
    },
    //来源状态初始化
    showOrdersource(row, column, cellValue, index) {
      if (cellValue == "1") {
        return "系统配送商";
      } else if (cellValue == "2") {
        return "自定义配送商";
      }
    },
    // 获取分页数据
    findPage: function(params) {
      let this_ = this;
      if (params == undefined || params == null) {
        params = {
          pageNum: this_.pageRequest.pageNum,
          pageSize: this_.pageRequest.pageSize
        };
      }
      if (this_.filters == undefined || this_.filters == null) {
        this_.filters = {};
      }
      this_.filters.start = params.pageNum;
      this_.filters.limit = params.pageSize;
      this.utils.request.queryOrderLogisticsCompany(this_.filters, function(
        res
      ) {
        if (res.data.rows == null) {
          res.data.rows = [];
        }
        this_.pageResult = res.data.rows;
        this_.totalSize = Number(res.data.total);
      });
    },
    // 显示新增界面
    handleAdd: function() {
      this.showLogo = true;
      this.deliveryCompanyNameShow = true;
      this.deliverySelectCompanyNameShow = false;
      this.logisticsCompanyNoDisabled = false;
      this.dataForm = {
        status: 1,
        logisticsCompanyName: "",
        logisticsCompanyNo: "",
        logisticsCompanyLogo: "",
        telephone: "",
        source: 2
      };
      this.fileList = [];
      this.editDialogVisible = true;
      this.operation = true;
      this.$nextTick(() => {
        this.$refs["dataForm"].clearValidate();
      });
    },
    //选择框
    selectionChange: function(params) {
      this.checked = params.selections;
    },
    // 批量删除
    handleDelete: function(data) {
      let this_ = this;
      let flag = true;
      if (this_.checked.length > 0) {
        $.each(this.checked, function(index, val) {
          if (val.source == 1) {
            this_.$message({
              message: "系统配送商不可删除",
              type: "error"
            });
            flag = false;
            return flag;
          }
        });
      }
      if (flag) {
        var ids = "";
        for (var i = 0; i < data.params.length; i++) {
          ids = ids + data.params[i].id + ",";
        }
        let param = {};
        param.ids = ids;
        this.utils.request.deleteOrderLogisticsCompany(
          param,
          this.deletInfoBack
        );
      }
    },
    // 删除修改回调
    deletInfoBack: function(data) {
      if (data.code == "0000") {
        this.$message({ message: "操作成功", type: "success" });
      } else {
        this.$message({ message: "操作失败, " + data.msg, type: "error" });
      }
      this.findPage();
    },
    // 显示编辑界面
    handleEdit: function(params) {
      if (this.$refs["dataForm"] != undefined) {
        this.$refs["dataForm"].clearValidate();
      }
      if (params.row.status == 1) {
        this.deliveryCompanyNameShow = false;
        this.deliverySelectCompanyNameShow = true;
        this.logisticsCompanyNoDisabled = true;
        this.showLogo = false;
      } else {
        this.deliveryCompanyNameShow = true;
        this.deliverySelectCompanyNameShow = false;
        this.logisticsCompanyNoDisabled = false;
        this.showLogo = true;
      }
      this.dataForm = {
        id: params.row.id,
        status: params.row.source,
        logisticsCompanyName: params.row.logisticsCompanyName,
        logisticsCompanyNo: params.row.logisticsCompanyNo,
        telephone: params.row.telephone,
        source: params.row.status
      };
      if (
        params.row.logisticsCompanyLogo != null &&
        params.row.logisticsCompanyLogo != ""
      ) {
        let imgUrl = {};
        imgUrl.name = 1;
        imgUrl.url = params.row.logisticsCompanyLogo;
        this.fileList.push(imgUrl);
      }
      this.editDialogVisible = true;
      this.operation = false;
      // this.$nextTick(function () {
      //   this.dataForm = Object.assign({}, params.row);
      // });
    },
    // 编辑
    submitForm: function() {
      this.$refs.dataForm.validate(valid => {
        if (valid) {
          this.$confirm("确认提交吗？", "提示", {}).then(() => {
            let params = Object.assign({}, this.dataForm);
            var this_ = this;
            // if(this_.dataForm.source==1){
            //   params.logisticsCompanyName=this_.dataForm.logisticsCompanyName.deliveryCompanyName
            // }
            this.utils.request.editOrderLogisticsCompany(params, function(res) {
              if (res.code == "0000") {
                this_.$message({ message: "操作成功", type: "success" });
                this_.$refs["dataForm"].resetFields();
                this_.editDialogVisible = false;
                this_.findPage(null);
              } else {
                this_.$message({
                  message: "操作失败, " + res.msg,
                  type: "error"
                });
              }
            });
          });
        }
      });
    },

    // 时间格式化
    dateFormat: function(row, column, cellValue, index) {
      return format(row[column.property]);
    },

    resetForm(formName) {
      if (this.$refs[formName] != undefined) {
        this.$refs[formName].resetFields();
        this.filters.start_time = "";
        this.filters.end_time = "";
        this.findPage(null);
      }
    },

    // 处理表格列过滤显示
    displayFilterColumnsDialog: function() {
      this.$refs.tableColumnFilterDialog.setDialogVisible(true);
    },
    // 处理表格列过滤显示
    handleFilterColumns: function(data) {
      this.filterColumns = data.filterColumns;
      this.$refs.tableColumnFilterDialog.setDialogVisible(false);
    },
    // 处理表格列过滤显示
    initColumns: function() {
      let temp = [];

      $.each(this.columns, function(key, val) {
        temp.push(val);
      });
      this.filterColumns = temp;
    },
    //列表下载
    downloadExcel() {
      this.$confirm("确定下载列表文件?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          this.exportData(this.filters, this.filterColumns, "换货管理下载");
        })
        .catch(() => {});
    },
    //导出操作
    exportData(filters, filterColumns, fileName) {
      let this_ = this
      if (filters == undefined || filters == null) {
        filters = {};
      }
      this_.utils.request.queryOrderLogisticsCompany(filters, function(res) {
        for (var i = 0; i < res.data.total; i++) {
          res.data.rows[i].source = this_.showOrdersource(null,null,parseInt(res.data.rows[i].source),null);
          res.data.rows[i].status = this_.showOrderStatus(null,null,parseInt(res.data.rows[i].status),null);
        }
        exportExcel(res.data.rows, filterColumns, fileName);
      });
    },
    changeRadio(e) {
      if (e === "1") {
        this.deliveryCompanyNameShow = false;
      } else {
        this.deliveryCompanyNameShow = true;
      }
    }
  },
  mounted() {
    this.initColumns();
    this.queryExpressMapConfig();
  }
};
</script>

<style lang='scss' scoped>
.pt20 {
  padding-bottom: 20px;
}
</style>
